﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Dual licensed under the MIT and GPL licenses:
//  http://www.opensource.org/licenses/mit-license.php
//  http://www.gnu.org/licenses/gpl.html

using System;
using System.Collections.Generic;
using System.Web;
using DNA.OpenAPI.Atom;
using DNA.OpenAPI.OpenSearch;
using DNA.OpenAPI.Rss;
using System.Linq;

namespace DNA.Mvc.Community
{
    public class PostSearchProvider : OpenSearchProvider
    {
        private IForumContext forumContext;

        public PostSearchProvider(IForumContext dbContext)
        {
            forumContext = dbContext;
        }

        public override string Name
        {
            get
            {
                return "forums";
            }
            set
            {
                base.Name = value;
            }
        }

        public override string Title
        {
            get { return "Forums"; }
        }

        public override bool SupportSuggestion
        {
            get
            {
                return true;
            }
        }

        public override IEnumerable<OpenSearchSuggestion> Suggest(string searchTerms, int count)
        {
            var comparer = new OpenSearchSuggestionComparer();
            return forumContext.Posts.Filter(p => p.Title.StartsWith(searchTerms))
                .ToList()
                .Select(p => new OpenSearchSuggestion() { SearchTerms = p.Title })
                .Distinct(comparer)
                .Take(count);
        }

        public override IEnumerable<AtomEntry> GetAtomResult(string searchTerms, int pageIndex, int pageSize, out int totalRecords)
        {
            var postsQuery = forumContext.Posts.Filter(p => p.Title.Contains(searchTerms) || p.Body.Contains(searchTerms));

            var entries = new List<AtomEntry>();
            totalRecords = postsQuery.Count();
            var skip = (pageIndex - 1) * pageSize;
            if (skip == 0) skip = 0;

            var posts = postsQuery.OrderByDescending(p => p.ID).Skip(skip).Take(pageSize);

            foreach (var post in posts)
            {
                try
                {
                    var summary = TextUtility.ClearHtml(post.Body);
                    if (summary.Length > 255)
                        summary = summary.Substring(0, 255) + "...";
                    string permaLink = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + UrlUtility.CreateUrlHelper().Action("Index", "Thread", new { Area = "community", id = post.ThreadID }) + "#" + post.ID.ToString();

                    var builder = new AtomEntryBuilder(post.Title, permaLink);
                    builder.SetSummary(summary);
                    builder.SetPublished(post.Posted);
                    builder.SetContent(post.Body, src: permaLink);
                    builder.SetAuthor(post.UserName, email: System.Web.Security.Membership.GetUser(post.UserName).Email);
                    builder.SetLastUpdated(post.LastModified);
                    //if (!string.IsNullOrEmpty(article.ImageUrl))
                    //    builder.AddLink(article.ImageUrl, type: "image/png");
                    builder.AddLink(permaLink);
                    //var cats = article.GetCategories();
                    //if (cats.Count() > 0)
                    //    builder.AddCategories((from c in cats select new AtomCategory() { Text = c.Title, Term = c.Title, Scheme = c.GetPermalinkUrl().ToString() }).ToList());
                    entries.Add(builder.Entry);
                }
                catch { continue; }
            }
            return entries;
        }

        public override IEnumerable<RssItem> GetRssResult(string searchTerms, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }
    }
}